package com.man.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.man.common.Result;
import com.man.pojo.DpMessagesDTO;
import com.man.pojo.HistoryMessageDTO;
import com.man.pojo.Messages;
import com.man.pojo.messageResponse.ChatCompletion;
import com.man.service.DpService;
import com.man.util.NetWorkUtil;
import com.man.util.SerializationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Semaphore;


@Service
@Slf4j
public class DpServiceImpl implements DpService {

    private final Semaphore semaphore = new Semaphore(1); // 限制同时只有一个线程可以进入

    @Value("${myDeepSeek.dpUrl.seedMessage}")
    private String dpUrl;

    @Value("${myDeepSeek.pic.user}")
    private String userPic;

    @Value("${myDeepSeek.pic.robot}")
    private String robotPic;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    @Async
    public Result<String> sendMessages(String content, String username) {
        try {
            semaphore.acquire(); // 获取许可
            // 在这里实现消息处理逻辑
            log.info("获取许可：username: {}, content: {}", username, content);

            List<Messages> messagesList = new ArrayList<>();

            String historyContent = (String) redisTemplate.opsForValue().get(username);
            if (historyContent != null && !historyContent.isEmpty()) {
                // 使用工具类反序列化历史对话为Messages对象，并加入到historyMessages中
                TypeReference<List<Messages>> typeRef = new TypeReference<>() {};
                List<Messages> deserializedMessages = SerializationUtil.deserialize(historyContent, typeRef);
                messagesList.addAll(deserializedMessages);
            }

            // 构建本次请求对话内容
            Messages messages = new Messages("user", content);

            // 先将问题加入到历史对话中
            messagesList.add(messages);

            // 将历史对话发过去
            DpMessagesDTO dpMessagesDTO = DpMessagesDTO.builder()
                    .messages(messagesList)
                    .model("deepseek-r1:14b")
                    .temperature(0.7)
                    .build();

            // 发送请求获取相应
            String response = NetWorkUtil.sendPost(dpUrl, dpMessagesDTO);
            ChatCompletion chatCompletion = new ObjectMapper().readValue(response, ChatCompletion.class);

            String answer = chatCompletion.getChoices().get(0).getMessage().getContent();

            // 将历史对话存入redis
            Messages reMessage = new Messages("assistant", answer);
            messagesList.add(reMessage);
            redisTemplate.opsForValue().set(username, SerializationUtil.serialize(messagesList));

            log.info("send: {}", content);
            log.info("response: {}", response);

            return Result.success(answer);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } finally {
            semaphore.release(); // 释放许可
        }

        return Result.success("请稍后再试");
    }

    @Override
    public Result<List<HistoryMessageDTO>> getHistoryMessages(String username) {
        List<HistoryMessageDTO> historyMessages = new ArrayList<>();

        // 从redis中获取历史对话
        String historyContent = (String) redisTemplate.opsForValue().get(username);

        if (historyContent == null || historyContent.isEmpty()) {
            log.info("获取历史信息为空：username: {}", username);
            return Result.success(historyMessages);
        }

        // 使用工具类反序列化历史对话为Messages对象，并加入到historyMessages中
        TypeReference<List<Messages>> typeRef = new TypeReference<>() {};
        List<Messages> historyMessageList = SerializationUtil.deserialize(historyContent, typeRef);

        long messId = 1;
        for (Messages messages : historyMessageList) {
            HistoryMessageDTO build = HistoryMessageDTO.builder()
                    .id(messId)
                    .pic(messId % 2 == 1 ? userPic : robotPic)
                    .type(messId % 2 == 1 ? 1 : 0)
                    .content(messages.getContent())
                    .build();

            historyMessages.add(build);
            messId++;
        }

        log.info("获取历史信息成功：username: {}", username);
        return Result.success(historyMessages);
    }
}
